<script lang="ts" setup>

import {h, markRaw, onMounted, ref} from 'vue';
import type { VbenFormProps } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import { Page, useVbenModal } from '@vben/common-ui';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getSizeGroupList, doSizeGroupDelete } from '#/api/sizeGroup';
import { Button, message, Popconfirm, Input } from 'ant-design-vue';

import Form from './modules/form.vue';
import SizeModal from './modules/sizeModal.vue';
import TwoFields from "#/views/backend/modules/two-fields.vue";
import { AntPlusOutlined } from '@vben/icons';
import { useDebounceFn } from '@vueuse/core'
const params = ref<any>({
  quick_search: '',
});

// 获取选中的行数据
const selectedRows = ref<any>([]);

// 默认排序
const defaultSort: { field: string; order: '' | 'asc' | 'desc' | null } = {
  field: 'id',
  order: 'desc',
};

/**
 * 获取状态选项
 */
const getStatusOptions = () => {
  return [
    { label: '启用', value: 1, color: 'success' },
    { label: '禁用', value: 0, color: 'default' },
  ];
};

const formOptions: VbenFormProps = {
  wrapperClass: 'grid-cols-5',
  schema: [
    {
      component: markRaw(TwoFields),
      fieldName: 'id',
      disabledOnChangeListener: false,
      label: 'ID',
      operator: 'RANGE',
      valueToString: true,
      componentProps: {
        allowClear: true,
        placeholder: '范围筛选',
      },
    },
    {
      component: 'Input',
      fieldName: 'name',
      label: '尺码组名称',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
    },
    {
      component: 'Select',
      fieldName: 'status',
      label: '状态',
      operator: '=',
      componentProps: {
        allowClear: true,
        options: [
          { label: '启用', value: 1 },
          { label: '禁用', value: 0 },
        ],
        placeholder: '请选择状态',
      },
    },
    {
      component: 'RangePicker',
      fieldName: 'create_time',
      label: '创建时间',
      operator: 'RANGE',
      valueToString: true,
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
    },
    {
      component: 'RangePicker',
      fieldName: 'update_time',
      label: '更新时间',
      operator: 'RANGE',
      valueToString: true,
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
    },
  ],
  showCollapseButton: true,
  collapsed: true,
  submitOnEnter: true,
};

const gridOptions: VxeTableGridOptions = {
  border: true,
  checkboxConfig: {
    highlight: true,
    reserve: true,
    showReserveStatus: true,
  },
  height: 'auto',
  rowConfig: { useKey: true, keyField: 'id', isHover: true },
  columnConfig: { useKey: true },
  exportConfig: {},
  sortConfig: {
    defaultSort,
    remote: true,
  },
  proxyConfig: {
    ajax: {
      query: async ({ page, sort }) => {
        const search = await gridApi.formApi.getFiltersValues();
        const queryParams = {
          ...params.value,
          page: page.currentPage,
          limit: page.pageSize,
          search,
          quick_search: params.value.quick_search,
          order: sort.field && sort.order ? `${sort.field},${sort.order}` : `${defaultSort.field},${defaultSort.order}`,
        };

        const { list, total } = await getSizeGroupList(queryParams);

        return {
          items: list || [],
          total: total || 0,
        };
      },
    },
    sort: true,
  },
  columns: [
    { type: 'checkbox', width: 60, align: 'center', fixed: 'left' },
    {
      field: 'id',
      width: 70,
      title: 'ID',
      sortable: true,
      align: 'center',
    },
    {
      field: 'name',
      minWidth: 160,
      title: '尺码组名称',
      sortable: false,
      align: 'center',
    },
    {
      field: 'cate_tag_str',
      width: 120,
      title: '品类范围',
      sortable: false,
      align: 'center',
    },
    {
      field: 'status',
      width: 90,
      title: '状态',
      sortable: false,
      align: 'center',
      cellRender: {
        name: 'CellTag',
        options: getStatusOptions(),
      },
    },
    {
      field: 'create_time',
      width: 180,
      title: '创建时间',
      sortable: true,
      align: 'center',
    },
    {
      field: 'update_time',
      width: 180,
      title: '更新时间',
      sortable: true,
      align: 'center',
    },
    {
      field: 'operation',
      title: '操作',
      width: 200,
      align: 'center',
      fixed: 'right',
      slots: {
        default: 'operation',
      },
    },
  ],
  pagerConfig: {
    currentPage: 1,
    pageSize: 30,
    pageSizes: [30, 50, 100, 200, 300],
  },
  toolbarConfig: {
    custom: true,
    export: true,
    refresh: true,
    resizable: true,
    search: true,
    zoom: true,
  },
  id: 'size_group_list',
  customConfig: {
    storage: true,
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions,
  formOptions,
});

const gridEvents = {
  checkboxChange: () => {
    selectedRows.value = gridApi.grid.getCheckboxRecords();
  },
  checkboxAll: () => {
    selectedRows.value = gridApi.grid.getCheckboxRecords();
  },
};

/**
 * 新增
 */
const handleCreate = () => {
  formModalApi.setData({ info: {} }).open();
};

/**
 * 编辑
 */
const handleEdit = (row: any) => {
  formModalApi.setData({ info: row }).open();
};

/**
 * 删除
 */
const handleDelete = async (row: any) => {
  try {
    await doSizeGroupDelete({ ids: [row.id] });
    message.success('删除成功');
    gridApi.reload();
  } catch (error) {
    console.error('删除失败:', error);
  }
};


/**
 * 打开尺码管理弹窗
 */
const handleManageSize = (row: any) => {
  sizeModalApi.setData({ sizeGroupId: row.id, sizeGroupName: row.name }).open();
};

/**
 * 刷新表格
 */
const fetchData = async () => {
  if(gridApi){
    gridApi.reload();
  }

};
const debouncedReload = useDebounceFn(gridApi.reload, 1000)

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  onClosed: () => {
    // fetchData();
  },
});

const [SizeManageModal, sizeModalApi] = useVbenModal({
  connectedComponent: SizeModal,
  onClosed: () => {
    // fetchData();
  },
});
</script>

<template>
  <Page auto-content-height>
    <Grid v-bind="gridEvents">
      <template #toolbar-actions>
        <Button type="primary" @click="handleCreate">
          <AntPlusOutlined />
          新增
        </Button>
      </template>
      <template #toolbar-tools>
        <div>
          <Input type="text" placeholder="通过主键模糊搜索" v-model:value="params.quick_search" :allow-clear="true" @input="debouncedReload" />
        </div>
      </template>
      <template #operation="{ row }">
        <Button class="mr-2" type="primary" size="small" @click="handleManageSize(row)">
          尺码管理
        </Button>
        <Button class="mr-2" type="link" size="small" @click="handleEdit(row)">编辑</Button>
        <Popconfirm title="确定要删除吗？" @confirm="handleDelete(row)">
          <Button type="link" size="small" danger>删除</Button>
        </Popconfirm>
      </template>
    </Grid>
    <FormModal @fetch-data="fetchData" />
    <SizeManageModal @fetch-data="fetchData" />
  </Page>
</template>
